package com.wx.finance.biz.service.impl;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alipay.remoting.rpc.RpcClient;
import com.wx.common.dto.TokenResponse;
import com.wx.common.exception.BizException;
import com.wx.common.netty.NettyServerHelper;
import com.wx.common.netty.UserConnectionInfo;
import com.wx.common.sofabolt.SofaboltConfig;
import com.wx.common.sofabolt.SofaboltHelper;
import com.wx.common.sofabolt.SofaboltMsgRequest;
import com.wx.common.sofabolt.SofaboltMsgResponse;
import com.wx.finance.biz.service.SocketMsgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Service
@Slf4j
@RequiredArgsConstructor
public class SocketMsgServiceImpl<T extends SofaboltMsgRequest> implements SocketMsgService<T> {
    final NettyServerHelper nettyServerHelper;
    final RpcClient rpcClient;
    final SofaboltConfig sofaboltConfig;
    final SofaboltHelper sofaboltHelper;

    /**
     * 发送sofabolt消息
     *
     * @param request
     */
    @Override
    public void sendMsgByClientId(T request) {
        UserConnectionInfo userConnectionInfo = nettyServerHelper.getClientInfoFromRedis(request.getClientId());
        if (userConnectionInfo == null) {
            log.error("用户已下线：{}", request.getClientId());
            return;
        }
        request.setUserChannelId(userConnectionInfo.getChannelId());
        try {
            Instance instance = sofaboltHelper.getInstance(userConnectionInfo.getHost());

            if (instance == null) {
                throw new BizException("服务器：" + userConnectionInfo.getHost() + "，已下线");
            }
            String address = instance.getIp() + ":" + instance.getPort();
            SofaboltMsgResponse response = (SofaboltMsgResponse) rpcClient.invokeSync(address, request, 3000);
            log.info("Response from {}: {}", request.getServerAddress(), response.getMsg());
        } catch (Exception ex) {
            throw new BizException("发送消息失败", ex);
        }
    }
}